package com.xushu.query;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

public class MutilThreadQuery {
    private static final int TIMEOUT_MS = 200;


    // 1. Future
    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        List<Future<List<String>>> futures = new ArrayList<>();
        List<String> finalResult = Collections.synchronizedList(new ArrayList<>());

        long begin = System.currentTimeMillis();
        // 创建5个任务，每个任务调用一次接口
        for (int i = 0; i < 5; i++) {
            futures.add(executor.submit(() -> fetchDataFromAPI()));
        }

        // 等待所有任务完成并合并结果
        for (Future<List<String>> future : futures) {
            List<String> result = future.get();
            finalResult.addAll(result);
        }


        long end = System.currentTimeMillis();
        // 输出最终结果
        System.out.println("result size: " + finalResult);
        System.out.println("耗时: " + (end-begin));
        // 这里可以对结果进一步处理，例如返回给调用者
    }

    // 模拟调用接口的方法
    private static List<String> fetchDataFromAPI() throws InterruptedException {
        // 模拟接口调用延迟200ms
        Thread.sleep(200);
        List<String> data = new ArrayList<>();
        for (int i = 0; i < 200; i++) {
            data.add("Data " + i);
        }
        return data;
    }
}